package com.lanyou.cook.test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;

public class SendRequest {
	public static void main(String[] args) throws HttpException, IOException,
			URISyntaxException {
		ScheduledExecutorService pool = Executors
				.newSingleThreadScheduledExecutor();
		Runnable runable = new Runnable() {

			@Override
			public void run() {
				System.out.println("执行定时发送请求任务开始");
				try {
					int times = RandomUtils.nextInt(100);
					while (times-- > 0) {
						SendRequest.sendRequest();
					}
					System.out.println("执行定时发送请求任务结束");
				} catch (HttpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		pool.scheduleAtFixedRate(runable, 5, 3, TimeUnit.SECONDS);

		// String result = SendRequest.sendRequest();
		// System.out.println(result);
	}

	public static String sendRequest() throws HttpException, IOException,
			URISyntaxException {
		String parameter = getParameter();
		String method = "post";
		String url = "http://localhost:8181/40287d815180f8bf015180fb39f200a4/v1.0/getDatabaseInfo/";
		String contentType = "text/xml; charset=utf-8";

		String responseMsg = "";

		HttpRequest request = new BasicHttpEntityEnclosingRequest(method, url);
		// 添加输入流
		byte[] b = parameter.getBytes("UTF-8");
		InputStream is = new ByteArrayInputStream(b, 0, b.length);
		((BasicHttpEntityEnclosingRequest) request)
				.setEntity(new InputStreamEntity(is, b.length));

		request.addHeader("Content-Type", contentType);

		int statusCode = 200;
		try {
			// 最后生成一个HttpClient对象，并发出postMethod请求
			HttpClient httpClient = new DefaultHttpClient();
			HttpHost httpHost = new HttpHost(URIUtils.extractHost(new URI(url)));
			HttpResponse response = httpClient.execute(httpHost, request);
			// statusCode = response.getStatusLine().getStatusCode();
			// if (200 == statusCode) {
			// try {
			// InputStream inputStream = response.getEntity().getContent();
			// BufferedReader reader = new BufferedReader(
			// new InputStreamReader(inputStream));
			// StringBuilder builder = new StringBuilder();
			// String line;
			// do {
			// line = reader.readLine();
			// builder.append(line);
			// } while (line != null && !"".equals(line));
			// responseMsg = builder.toString();
			// } catch (Exception e) {
			// responseMsg = "调用失败！错误码："
			// + response.getStatusLine().getStatusCode() + ":"
			// + response.getStatusLine().getReasonPhrase();
			// }
			// } else {
			// responseMsg = response.getStatusLine().getReasonPhrase();
			// responseMsg = "调用失败！错误码：" + statusCode + "。详细信息："
			// + URLDecoder.decode(responseMsg, "UTF-8");
			// }

		} catch (Exception e) {
			responseMsg = e.getMessage();
		}
		return responseMsg;
	}

	private static String getParameter() {
		String msg = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">"
				+ "<soapenv:Header><web:EsbHead><CallSystemCode>40287d815180f8bf015180fb38df00a0</CallSystemCode><ApplyKey>651751b4-ff55-4b38-9886-34a9b1057a3a</ApplyKey><AccessToken></AccessToken></web:EsbHead></soapenv:Header>"
				+ "<soapenv:Body>"
				+ "<web:getDatabaseInfo/>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";
		return msg;
	}
}
